#include "stdafx.h"
#include "base_stream.h"


uint_32 byte_stream_read(tag_base_stream * src, void * dst, uint_32 length)
{
	byte_stream_t * bs = (byte_stream_t *)src;

	memcpy_s(dst, length, bs->bytes + bs->curr, length);
	bs->curr += length;
	return length;
}

int_32 byte_stream_seek(tag_base_stream * src, int_32 length, stream_seek_e seek)
{
	byte_stream_t * bs = (byte_stream_t *)src;
	switch(seek)
	{
	case stream_seek_begin:
		bs->curr = length;
		break;
	case stream_seek_end:
		bs->curr = bs->length - length;
		break;
	case stream_seek_curr:
		bs->curr += length;
		break;
	case stream_seek_tell:
		break;
	}
	return bs->curr;
}

void create_byte_stream(byte_stream_t * stream, uint_8 * buffer, uint_32 length)
{
	stream->base.reader = byte_stream_read;
	stream->base.seeker = byte_stream_seek;
	stream->bytes = buffer;
	stream->length = length;
	stream->curr = 0;
}





uint_32 file_stream_read(tag_base_stream * src, void * dst, uint_32 length)
{
	file_stream_t * fs = (file_stream_t *)src;
	size_t ret = fread_s(dst, length, length, 1, fs->file);
	if(ret >= 0)
		return (uint_32)ret;
	else
		return UI32_MAX;
}

int_32 file_stream_seek(tag_base_stream * src, int_32 length, stream_seek_e seek)
{
	file_stream_t * fs = (file_stream_t *)src;
	int_32 flags = 0;
	switch(seek)
	{
	case stream_seek_begin:
		flags = SEEK_SET;
		break;
	case stream_seek_end:
		flags = SEEK_END;
		break;
	case stream_seek_curr:
		flags = SEEK_CUR;
		break;
	case stream_seek_tell:
		return (uint_32)ftell(fs->file);
		//break;
	}
	return (uint_32)fseek(fs->file, length, flags);
}


void create_file_stream(file_stream_t * stream, const char_x * file)
{
	_tfopen_s(&stream->file, file, _T("rb"));
	stream->base.reader = file_stream_read;
	stream->base.seeker = file_stream_seek;
}
void destroy_file_stream(file_stream_t * stream)
{
	fclose(stream->file);
}